package com.tee.live.im.core.server.handler;

import com.tee.live.im.core.server.common.ChannelHandlerContextCache;
import com.tee.live.im.core.server.common.ImContextAttr;
import com.tee.live.im.core.server.common.ImMsg;
import com.tee.live.im.core.server.factory.ImHandlerFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

/**
 * @author tee
 * @date 2025/10/22
 */
@Component
public class ImServerCoreHandler extends SimpleChannelInboundHandler {

    private ImHandlerFactory imHandlerFactory = new ImHandlerFactoryImpl();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ImMsg)) {
            throw new IllegalAccessException("err msg, msg is:" + msg);
        }
        ImMsg imMsg = (ImMsg) msg;

        // 消息业务分发code
        imHandlerFactory.doMsgHandler(ctx, imMsg);
    }

    /**
     * 正常或者意外断线都会触发到这里
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(final ChannelHandlerContext ctx) throws Exception {

        Long userId = ctx.attr(ImContextAttr.USER_ID).get();
        ChannelHandlerContextCache.remove(userId);

    }

}
